package com.dolawing.phonecallapp.listenphonecall;

import android.annotation.SuppressLint;
import android.app.ActivityManager;
import android.app.job.JobInfo;
import android.app.job.JobParameters;
import android.app.job.JobScheduler;
import android.app.job.JobService;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.os.PowerManager;
import android.util.Log;
import android.widget.Toast;

import androidx.annotation.NonNull;

import com.dolawing.phonecallapp.keepAliveService.LocalService;

import java.util.Date;
import java.util.List;

public class JobSchedulerService extends JobService {
    private int kJobId = 0;

    private Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(@NonNull Message msg) {
            JobParameters parameters = (JobParameters) msg.obj;
            //检查 Service是否存活
            boolean isLocalServiceWork = isServiceWork(JobSchedulerService.this, "com.dolawing.phonecallapp.listenphonecall.CallListenerService");
            if (!isLocalServiceWork) {
                Intent intent = new Intent(JobSchedulerService.this, CallListenerService.class);
//                JobSchedulerService.this.stopService(intent);
                JobSchedulerService.this.startService(intent);
                Log.i("INFO","process start CallListenerService");
            }
            isLocalServiceWork = isServiceWork(JobSchedulerService.this, "com.dolawing.phonecallapp.keepAliveService.LocalService");
            if (!isLocalServiceWork) {
                Intent intent = new Intent(JobSchedulerService.this, LocalService.class);
//                JobSchedulerService.this.stopService(intent);
                JobSchedulerService.this.startService(intent);
                Log.i("INFO","process start LocalService");
            }

            //第一个参数JobParameters，第二个参数表示出错时是否重复执行
            jobFinished(parameters,false);
            return true;
        }

    });

    @Override
    public void onCreate() {
        super.onCreate();
        Log.i("INFO", "jobService create");
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.i("INFO", "jobService start");
        // 在服务启动时，直接将任务推到JobScheduler 的任务队列,然后在设定的时间条件到达时，便会直接吊起我们的服务，走onStartJob()方法
        scheduleJob(getJobInfo());
        return START_NOT_STICKY;
    }

    @Override

    public void onDestroy() {
        super.onDestroy();
    }

    @Override
    public boolean onStartJob(JobParameters params) {
//        params.getExtras()
//        scheduleJob(getJobInfo());
        //睡眠唤醒
        PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
        @SuppressLint("InvalidWakeLockTag")
        PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.ACQUIRE_CAUSES_WAKEUP |
                PowerManager.SCREEN_BRIGHT_WAKE_LOCK, "bright");
        wl.acquire();
        wl.release();
        //发送数据异步处理
        Message message = Message.obtain();
        message.obj = params;
        handler.sendMessage(message);
        Date times = new Date();
        Log.e("后台数据",times.toString());
        // 在服务启动时，直接将任务推到JobScheduler 的任务队列,然后在设定的时间条件到达时，便会直接吊起我们的服务，走onStartJob()方法
        scheduleJob(getJobInfo());  //重复执行
        return true;
    }

    @Override
    public boolean onStopJob(JobParameters params) {
        Log.i("INFO", "job stop");
        // 当执行完毕时，我们再将任务加入到 JobScheduler 里面就可以了。
//        scheduleJob(getJobInfo());
        return true;
    }

    /**
     * Send job to the JobScheduler.
     */
    public void scheduleJob(JobInfo t) {
        Log.i("INFO", "Scheduling job");
        JobScheduler tm  = (JobScheduler) getSystemService(Context.JOB_SCHEDULER_SERVICE);
        if (tm != null) {
            tm.schedule(t);
        }
    }

    public JobInfo getJobInfo() {
        int min = 10 ;  //JobInfo.DEFAULT_INITIAL_BACKOFF_MILLIS
        JobInfo.Builder builder = new JobInfo.Builder(1, new ComponentName(this, JobSchedulerService.class));
        if (Build.VERSION.SDK_INT>=Build.VERSION_CODES.N){
            builder.setMinimumLatency(min * 60 * 1000); //执行的最小延迟时间，与setPeriodic(long time)不兼容
            builder.setOverrideDeadline(min * 60 * 1000); //执行的最长延时时间,与setPeriodic(long time)不兼容
            builder.setBackoffCriteria(JobInfo.DEFAULT_INITIAL_BACKOFF_MILLIS, JobInfo.BACKOFF_POLICY_LINEAR);//线性重试方案
        }else{
            builder.setPeriodic(min * 60 * 1000); //间隔时间--周期 1000ms = 1s, 设置15分钟
        }

        builder.setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY);  //无网络也执行
        builder.setPersisted(true);  // 设置设备重启时，执行该任务
        builder.setRequiresCharging(false);  // 当插入充电器，执行该任务
        builder.setRequiresDeviceIdle(false); //用户没有使用该设备且有一段时间时,才启动该任务
        return builder.build();
    }

    /**
     * 判断某个服务是否正在运行的方法
     * @param mContext
     * @param serviceName 是包名+服务的类名（例如：net.loonggg.testbackstage.TestService）
     * @return true代表正在运行，false代表服务没有正在运行
     */
    public boolean isServiceWork(Context mContext, String serviceName) {
        boolean isWork = false;
        ActivityManager myAM = (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningServiceInfo> myList = null;
        if (myAM != null) {
            myList = myAM.getRunningServices(Integer.MAX_VALUE);
        }
        if (myList != null && myList.size() <= 0) {
            return false;
        }
        if (myList != null) {
            for (int i = 0; i < myList.size(); i++) {
                String mName = myList.get(i).service.getClassName();
                if (mName.equals(serviceName)) {
                    isWork = true;
                    break;
                }
            }
        }
        return isWork;

    }
}
